<template>
  <div class="components-basic-set">
    <el-form
      ref="dataFormRef"
      class="set-form"
      label-position="left"
      :model="dataForm"
      @submit.prevent
    >
      <div class="title">
        {{ $t('distribution.basicDistributionSet') }}
      </div>
      <!-- 分销开关 -->
      <el-form-item :label="$t('distribution.distributionSwitch')">
        <el-radio-group v-model="dataForm.distributionSwitch">
          <el-radio :label="0">
            {{ $t('seckill.close') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('seckill.open') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 业绩归属 -->
      <el-form-item :label="$t('distribution.performanceAttribution')">
        <el-radio-group v-model="dataForm.attribution">
          <el-radio :label="0">
            {{ $t('distribution.paTip1') }}
            <el-tooltip
              class="item"
              effect="light"
              placement="right"
            >
              <template #content>
                <div
                  class="performanceAttribution-content"
                >
                  {{ $t('distribution.promptPaTip1') }}
                </div>
              </template>
              <el-icon color="#155bd4">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
          <el-radio :label="1">
            {{ $t('distribution.paTip2') }}
            <el-tooltip
              class="item"
              effect="light"
              placement="right"
            >
              <template #content>
                <div
                  class="performanceAttribution-content"
                >
                  {{ $t('distribution.promptPaTip2') }}
                </div>
              </template>
              <el-icon color="#155bd4">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 申请条件-条件审核判定 -->
      <el-form-item :label="$t('distribution.conditionalAuditJudgment')">
        <el-radio-group
          v-model="dataForm.autoCheck"
          @change="onChangeRadio(dataForm.autoCheck)"
        >
          <el-radio :label="0">
            {{ $t('distribution.manualJudgment') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('distribution.systemJudgment') }}
          </el-radio>s
          <el-radio :label="2">
            {{ $t('distribution.noAuditRequired') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 申请条件 -->
      <el-form-item
        v-if="dataForm.autoCheck === 1"
        :label="$t('distribution.applicationConditions')"
      >
        <div>
          <div class="">
            <el-checkbox v-model="isProd">
              {{ $t('distribution.purchaseDesignatedGoods') }}
            </el-checkbox>
            <el-button
              v-if="isProd"
              plain
              @click="prodsSelectHandle"
            >
              {{ $t('coupon.selectGoods') }}
            </el-button>
            <span class="tips">{{ $t('distribution.buyConditionTip2') }}</span>
            <div
              v-if="isProd"
              class="prod-list"
            >
              <div
                v-for="(prod, index) in productVOList"
                :key="index"
                style="margin: 5px 10px 0 0;"
              >
                <el-card
                  :body-style="{ padding: '0px' }"
                  style="height: 160px;width: 120px"
                >
                  <ImgShow
                    :src="prod.pic"
                    height="104"
                  />
                  <div class="card-prod-info-btn">
                    <div class="prod-name">
                      {{ prod.prodName }}
                    </div>
                    <div class="del-btn">
                      <span @click="onDeleteProd(index)">{{ $t('text.delBtn') }}</span>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>

          <div class="input-group">
            <el-checkbox
              v-model="isExpenseNumber"
              class="input-checked"
              @change="onRemoveExpenseNumber"
            >
              {{ $t('distribution.bcTip3') }}
            </el-checkbox>
            <el-form-item prop="expenseNumber">
              <el-input
                v-model="dataForm.expenseNumber"
                type="number"
                min="1"
                :disabled="!isExpenseNumber"
                style="width:240px"
                @change="onCheckNumber"
              >
                <template #append>
                  {{ $t('distribution.bcTip4') }}
                </template>
              </el-input>
            </el-form-item>
            <span class="tips">{{ $t('distribution.bcTip5') }}</span>
          </div>

          <div class="input-group">
            <el-checkbox
              v-model="isExpenseAmount"
              class="input-checked"
              @change="onRemoveExpenseAmount"
            >
              {{ $t('distribution.dbcTip1') }}
            </el-checkbox>
            <el-form-item prop="expenseAmount">
              <el-input
                v-model="dataForm.expenseAmount"
                type="number"
                min="0"
                style="width:240px"
                :disabled="!isExpenseAmount"
                @change="onCheckAmount"
              >
                <template #append>
                  {{ $t('distribution.dbcTip2') }}
                </template>
              </el-input>
            </el-form-item>
            <span class="tips">{{ $t('distribution.dbcTip3') }}</span>
          </div>
        </div>
      </el-form-item>
      <!-- 申请所需信息 -->
      <el-form-item
        v-if="dataForm.autoCheck !== 2"
        :label="$t('distribution.applyNeedInfo')"
      >
        <el-checkbox v-model="dataForm.realName">
          {{ $t('distribution.realName') }}
        </el-checkbox>
        <el-checkbox v-model="dataForm.identityCardNumber">
          {{ $t('distribution.idCardNo') }}
        </el-checkbox>
        <el-checkbox v-model="dataForm.identityCardPic">
          {{ $t('distribution.idCardPhoto') }}
        </el-checkbox>
      </el-form-item>
      <!-- 提现发放方式 -->
      <el-form-item :label="$t('distribution.Withdrawal')+':'">
        &nbsp;
        <el-tooltip
          class="item"
          effect="light"
          :content="$t('distribution.WithdrawalTip')"
          placement="right"
          style="color: #155BD4;"
        >
          <el-icon color="#155bd4">
            <QuestionFilled />
          </el-icon>
        </el-tooltip>
        &nbsp;
        <el-radio-group v-model="dataForm.withdrawal">
          <!-- 提现发放方式：0.无需审核直接发放，1.审核后系统发放，2.审核后人工发放 -->
          <el-radio :label="0">
            {{ $t('distribution.Issued1') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('distribution.Issued2') }}
            <el-tooltip
              effect="light"
              :content="$t('distribution.WithdrawalTip2')"
              placement="right"
              style="color: #155BD4;"
            >
              <el-icon color="#155bd4">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </el-radio>
          <el-radio :label="2">
            {{ $t('distribution.Issued3') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 提现设置start -->
      <el-divider content-position="left" />

      <div class="title">
        {{ $t("distribution.withdrawalSettings") }}
      </div>
      <el-form-item :label="$t('distribution.settlementTime')">
        <el-radio-group v-model="dataForm.settlementTime">
          <el-radio :label="0">
            {{
              $t("distribution.commissionSettled")
            }}
          </el-radio>
          <el-radio :label="1">
            {{
              $t("distribution.protectionPeriod")
            }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 单笔提现 -->
      <el-form-item :label="$t('withdraw.eachWithdrawal')">
        <el-input
          v-model.number="dataForm.amountMin"
          style="width: 180px"
          oninput="value=value.replace(/\D/g, '')"
          maxlength="10"
        >
          <template #append>
            {{ $t('distribution.dbcTip2') }}
          </template>
        </el-input>
        <span class="input-tips">,{{ $t('withdraw.tip2') }}</span>
        <el-input
          v-model.number="dataForm.amountMax"
          style="width: 180px"
          oninput="value=value.replace(/\D/g, '')"
          maxlength="10"
        >
          <template #append>
            {{ $t('distribution.dbcTip2') }}
          </template>
        </el-input>
        <span class="tips">{{ $t('withdraw.tip3') }}</span>
      </el-form-item>
      <!-- 提现频次 -->
      <el-form-item :label="$t('withdraw.withdrawalFrequency')">
        <el-select
          v-model="dataForm.frequency"
          :placeholder="$t('user.pleaseSelect')"
        >
          <el-option
            :label="$t('withdraw.everyDay')"
            :value="1"
          />
          <el-option
            :label="$t('withdraw.weekly')"
            :value="7"
          />
          <el-option
            :label="$t('withdraw.monthly')"
            :value="30"
          />
          <el-option
            :label="$t('withdraw.unlimited')"
            :value="-1"
          />
        </el-select>

        <el-input
          v-if="dataForm.frequency !== -1"
          v-model.number="dataForm.number"
          style="width: 180px"
          oninput="value=value.replace(/\D/g, '')"
          maxlength="10"
        >
          <template #append>
            {{ $t('distribution.bcTip4') }}
          </template>
        </el-input>
      </el-form-item>
      <!-- 提现说明 -->
      <el-form-item :label="$t('withdraw.withdrawalInstructions')">
        <el-input
          v-model="dataForm.paymentExplain"
          type="textarea"
          style="width: 300px"
          witdt="230"
          maxlength="50"
          show-word-limit
        />
        <br>
        <span class="tips">{{ $t('withdraw.tip4') }}</span>
      </el-form-item>
      <!-- 提现设置end -->
    </el-form>
    <div
      class="default-btn"
      @click="onSubmit()"
    >
      {{ $t('distribution.save') }}
    </div>
    <ProdsSelect
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :activity-type="1"
      @refresh-select-prods="onSelectDistributionProds"
    />
  </div>
</template>

<script setup>
import ProdsSelect from '@/components/prods-select/index.vue'
import { ElMessage } from 'element-plus'
const dataFormRef = ref(null)

// 是否指定商品
const isProd = ref(false)
// 是否指定单数
const isExpenseNumber = ref(false)
// 是否指定消费
const isExpenseAmount = ref(false)
const productVOList = ref([])
const dataForm = ref({
  distributionSwitch: 0,
  attribution: 1,
  autoCheck: 0,
  expenseNumber: null,
  prodIdList: [],
  productVOList: [],
  expenseAmount: null,
  realName: false,
  identityCardPic: false,
  identityCardNumber: false,
  frequency: null,
  settlementTime: 0,
  amountMax: '',
  amountMin: '',
  paymentExplain: null,
  number: null,
  withdrawal: 2
})
// 设置数据
const onSetDate = (data) => {
  dataForm.value = data
  if (dataForm.value.productVOList == null) {
    dataForm.value.productVOList = []
  }
  productVOList.value = dataForm.value.productVOList
  if (dataForm.value.expenseNumber > 0) {
    isExpenseNumber.value = true
  }
  if (dataForm.value.expenseAmount > 0) {
    isExpenseAmount.value = true
  }
  if (dataForm.value.prodIdList != null && dataForm.value.prodIdList.length > 0) {
    isProd.value = true
  }
}
// 获取数据
const onGetData = () => {
  http({
    url: http.adornUrl('/admin/distributionConfig/info'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data !== null) {
      onSetDate(data)
    }
  })
}
onMounted(() => {
  onGetData()
})

// 提交表单
const onSubmit = () => {
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return
    }
    const prodIdList = []
    if (productVOList.value && isProd) {
      productVOList.value.forEach(element => {
        prodIdList.push(element.prodId)
      })
    }
    dataForm.value.prodIdList = prodIdList
    if (isProd.value && dataForm.value.prodIdList.length <= 0) {
      ElMessage({
        message: $t('marketing.pleaseSelectAProduct'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!isProd.value) {
      dataForm.value.prodIdList = []
    }
    if (dataForm.value.expenseNumber === '.' || dataForm.value.expenseNumber === '-' || dataForm.value.expenseAmount === '.' || dataForm.value.expenseAmount === '-') {
      return
    }
    if (isExpenseNumber.value && !dataForm.value.expenseNumber) {
      ElMessage({
        message: $t('distribution.errorIntegerTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (dataForm.value.amountMin < 1) {
      ElMessage({
        message: $t('withdraw.errotTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (dataForm.value.amountMax > 20000) {
      ElMessage({
        message: $t('withdraw.errorTip7'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (dataForm.value.amountMax < dataForm.value.amountMin) {
      ElMessage({
        message: $t('withdraw.errorTip2'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (isExpenseAmount.value && !dataForm.value.expenseAmount) {
      ElMessage({
        message: $t('distribution.decimalTip1'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (dataForm.value.autoCheck === 1) {
      if (!isExpenseNumber.value && !isProd.value && !isExpenseAmount.value) {
        ElMessage({
          message: $t('distribution.systemJudgmentTips'),
          type: 'error',
          duration: 1500
        })
        return
      }
    }
    if (dataForm.value.frequency !== -1 && dataForm.value.number < 1) {
      ElMessage({
        message: $t('withdraw.errorTip3'),
        type: 'error',
        duration: 1500
      })
      return
    }
    const param = toRaw(dataForm.value)
    http({
      url: http.adornUrl('/admin/distributionConfig'),
      method: 'post',
      data: http.adornData(param)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500
      })
    }).catch(() => {
    })
  })
}
/**
 * 切换选项数据初始化
 */
const onChangeRadio = (autoCheck) => {
  if (autoCheck === 0) {
    isProd.value = false
    dataForm.value.productVOList = []
    productVOList.value = []
    isExpenseNumber.value = false
    dataForm.value.expenseNumber = null
    isExpenseAmount.value = false
    dataForm.value.expenseAmount = null
  }
}
// 显示添加指定商品弹框
const prodsSelectRef = ref(null)
const prodsSelectVisible = ref(false)
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value.init(productVOList.value)
  })
}
// 商品选择回调
const onSelectDistributionProds = (prods) => {
  if (prods) {
    productVOList.value = []
    for (const i in prods) {
      productVOList.value.push(prods[i])
    }
  }
}
// 删除指定商品
const onDeleteProd = (index) => {
  productVOList.value.splice(index, 1)
}
// 清除消费次数数据
const onRemoveExpenseAmount = () => {
  dataForm.value.expenseAmount = null
}
// 清除消费金额数据
const onRemoveExpenseNumber = () => {
  dataForm.value.expenseNumber = null
}
// 消费次数上限校验
const onCheckNumber = () => {
  const inNumber = Math.round(parseInt(dataForm.value.expenseNumber))
  if (inNumber < 1) {
    dataForm.value.expenseNumber = 1
  } else {
    dataForm.value.expenseNumber = inNumber > 1000 ? 1000 : inNumber
  }
}
// 消费金额校验
const onCheckAmount = (expenseAmount) => {
  if (!expenseAmount) {
    return
  }
  const inAmount = parseFloat(dataForm.value.expenseAmount).toFixed(2)
  if (inAmount < 0) {
    dataForm.value.expenseAmount = 0
  } else {
    dataForm.value.expenseAmount = inAmount > 10000 ? 10000 : inAmount
  }
}
</script>
<style lang="scss" scoped>
.components-basic-set {
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
  background: #f2f2f6;
  padding: 20px 35px;
  height: 100%;
  border-bottom: 1px solid #dddce2;

  .input-group{
    display: flex;
  }
  .prod-list{
    display: flex;
  }
  .set-form {
    margin: 20px;
  }
  .tips {
    color: #9797a1;
    font-size: 12px;
  }
  .title {
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 700;
    display: inline-block;
    vertical-align: middle;
    padding-right: 20px;
  }
}
.performanceAttribution-content {
  max-width: 300px;
}
</style>
